<?php
/**
 * @version $Id: country.php 45 2011-09-27 08:12:07Z truongnhan0311 $
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();
jimport('joomla.application.component.model');  

class WrdModelDistric extends WrdModel 
{
    var $_data;
	var $_id;
	var $_total = null;
	var $_pagination = null;
	var $_limit = null;
	var $_limitstart = null;

	function __construct(){
		parent::__construct();
		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');
		
		$this->_limit = $mainframe->getUserStateFromRequest( $context.$view.'limit', 'limit', $mainframe->getCfg('list_limit'), 0);
		$this->_limitstart = $mainframe->getUserStateFromRequest( $context.$view.'limitstart', 'limitstart', 0 );

		$this->setState('limit', $this->_limit);
		$this->setState('limitstart', $this->_limitstart);
	}

	function getData(){
		
		if (empty($this->_data)){
			$query = $this->_buildQuery();
			$this->_db->setQuery( $query, $this->_limitstart, $this->_limit );
			$this->_data = $this->_db->loadObjectList();
		}
		return $this->_data;
	}

	function getTotal(){
		if (empty($this->_total)){
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}
		return $this->_total;
	}

	function getPagination(){
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->_limitstart, $this->_limit );
		}
		return $this->_pagination;
	}

	function _buildQuery(){
		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');

		$orderby 			= $this->_buildContentOrderBy();
		$search 			= $mainframe->getUserStateFromRequest( $context.$view.'search','search','','string');
		$filter_state 		= $mainframe->getUserStateFromRequest( $context.$view.'published','published',-1,'int');
		$filter_user 		= $mainframe->getUserStateFromRequest( $context.$view.'created_id','created_id',-1,'int');
		
		$search 			= JString::strtolower( $search );
		
		$where = array();

		if ( $search ){
			$where[] = 'c.name LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false );
		}
		if ( $filter_state != -1 ){
			$where[] = 'c.published = '.$filter_state;
		}
		if ( $filter_user  != -1){
			$where[] = 'c.created_id = '.$filter_user;
		}
		$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );
		$query = ' SELECT 
					u.name as user_name, 
					country.name as country_name,
					city.name as city_name,
                    c.id,
                    c.ordering, 
                    c.name as distric_name, 
                    c.created_date,  
                    c.published
                	FROM #__wrd_distric as c 
                	LEFT JOIN #__users as u ON c.created_id = u.id
                	LEFT JOIN #__wrd_country as country ON c.country_id = country.id
                	LEFT JOIN #__wrd_city as city ON c.city_id = city.id
                	'

		. $where
		. $orderby;
		return $query;
	}

	function _buildContentOrderBy(){
		$mainframe = &JFactory::getApplication();
		$context = JRequest::getCmd('option');
		$view = JRequest::getCmd('view');

		$filter_order     = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_author','filter_order','id' );
		$filter_order_Dir = $mainframe->getUserStateFromRequest( $context.$view.'filter_order_Dir',  'filter_order_Dir', '' );
		$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir;
		return $orderby;
	}
    
	function delete($cid = array()){
		$result = false;

		if (count( $cid )){
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );
			$query = 'DELETE FROM #__wrd_distric '
				. ' WHERE id IN ( '.$cids.' )';
			$this->_db->setQuery( $query );
			if(!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}

    
	function publish($cid = array(), $publish = 1){
		$user 	=& JFactory::getUser();

		if (count( $cid ))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );

			$query = 'UPDATE #__wrd_distric '
				. ' SET published = '.(int) $publish
				. ' WHERE id IN ( '.$cids.' )'
			;
			$this->_db->setQuery( $query );
			if (!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}
    
     //save to table $nametable
    function store($post,$tablename){
        $profile = JTable::getInstance($tablename, 'TableWrd');
        $profile->load();
        $profile->bind($post);
		if ($profile->store()) {
			return $profile->id;
		} else {
			return 0;
		}
  	}
  	
  	function getList(){
  		$query = 'SELECT id AS value, name AS text'
		. ' FROM #__wrd_distric WHERE published=1 order by ordering,name ASC';
		$this->_db->setQuery( $query );
		return $this->_db->loadObjectList();
  	}

	function getUserList(){

		$query = 'SELECT a.created_id as value , b.username as text FROM #__wrd_distric a LEFT JOIN #__users b ON a.created_id = b.id 
			GROUP BY a.created_id';
		
		$this->_db->setQuery( $query );
		return $this->_db->loadObjectList();
	}
  	
  	function getItem($id){
  		$query = 'SELECT * FROM #__wrd_distric WHERE id = '.$id;
		$this->_db->setQuery($query);
		return $this->_db->loadObject();
  	}
  	
	function saveorder($pks = null, $order = null,$tablename)
	{
		// Initialise variables.
		$table 	= JTable::getInstance($tablename, 'TableWrd');
		$conditions	= array();

		if (empty($pks)) {
			return JError::raiseWarning(500, JText::_($this->text_prefix.'_ERROR_NO_ITEMS_SELECTED'));
		}

		// update ordering values
		foreach ($pks as $i => $pk) {
			$table->load((int) $pk);

			if ($table->ordering != $order[$i]) {
				$table->ordering = $order[$i];

				if (!$table->store()) {
					$this->setError($table->getError());
					return false;
				}

				// Remember to reorder within position and client_id
				$found = false;

				foreach ($conditions as $cond) {
					if ($cond[1] == $condition) {
						$found = true;
						break;
					}
				}

				if (!$found) {
					$key = $table->getKeyName();
					$conditions[] = array ($table->$key, $condition);
				}
			}
		}

		// Execute reorder for each category.
		foreach ($conditions as $cond) {
			$table->load($cond[0]);
			$table->reorder($cond[1]);
		}

		// Clear the component's cache
		$this->cleanCache();

		return true;
	}
	
	public function reorder($pks, $delta = 0,$tablename){
		// Initialise variables.
		$table 	= JTable::getInstance($tablename, 'TableWrd');
		$pks	= (array) $pks;
		$result	= true;

		foreach ($pks as $i => $pk) {
			$table->reset();

			if ($table->load($pk)) {
				$where = array();
				

				if (!$table->move($delta, $where)) {
					$this->setError($table->getError());
					unset($pks[$i]);
					$result = false;
				}
			} else {
				$this->setError($table->getError());
				unset($pks[$i]);
				$result = false;
			}
		}

		if (empty($pks)) {
			$result = null;
		}

		// Clear the component's cache
		if ($result == true) {
			$this->cleanCache();
		}

		return $result;
	}
    
    /*
     * get district for statistic 
     */
    function getDistrictForStatistic(){
        $query = '
            SELECT
                `t`.id AS `value`,
                `t`.NAME AS `text`
            FROM #__wrd_distric `t`
            WHERE `t`.published = 1
                  AND `t`.is_feature = 1
            ORDER BY  `t`.ordering ASC
        ';
      
      
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }
    
    /*
     * get OTHER district for statistic 
     */
    function getOtherDistrictForStatistic(){
        $query = '
            SELECT
                `t`.id AS `id`
            FROM #__wrd_distric `t`
            WHERE `t`.published = 1
                  AND `t`.is_feature = 0
        	ORDER BY  `t`.ordering ASC
        ';
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }
}